package controller

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"goback/dao/accessDao"
	"goback/model"
	res "goback/model/resultDTO"
	"io"
	"net/http"
	"strconv"
)

func Init(g *gin.Engine) {
	g.GET("/getcall", func(c *gin.Context) {
		access := new(model.Access)
		h := c.Request.Header
		marshal, err := json.Marshal(h)
		if err != nil {
			return
		}
		access.Header = string(marshal)
		access.Body = ""
		//gin获取请求的url
		access.Url = c.Request.URL.String()
		//gin获取所有查询参数
		//返回的是什么格式
		access.Query = c.Request.URL.Query().Encode()
		//gin从请求头和请求获取ip
		access.Ip = c.ClientIP()
		if ipHeader := h.Get("X-Real-Path"); ipHeader == "" {
			fmt.Println("The X-Real-Path header is not present in the request.")
		} else {
			fmt.Printf("The value of X-Real-Path is: %s\n", ipHeader)
			access.Ip = ipHeader
		}
		err = accessDao.Save(access)
		c.JSON(http.StatusOK, res.Success(access))
	})
	g.POST("/postcall", func(c *gin.Context) {
		access := new(model.Access)
		h := c.Request.Header
		marshal, err := json.Marshal(h)
		if err != nil {
			return
		}
		access.Header = string(marshal)
		bodyBytes, err := io.ReadAll(c.Request.Body)
		access.Body = string(bodyBytes)
		//gin获取请求的url
		access.Url = c.Request.URL.String()
		//gin获取所有查询参数
		//返回的是什么格式
		access.Query = c.Request.URL.Query().Encode()
		//gin从请求头和请求获取ip
		access.Ip = c.ClientIP()
		if ipHeader := h.Get("X-Real-Path"); ipHeader == "" {
			fmt.Println("The X-Real-Path header is not present in the request.")
		} else {
			fmt.Printf("The value of X-Real-Path is: %s\n", ipHeader)
			access.Ip = ipHeader
		}
		err = accessDao.Save(access)
		c.JSON(http.StatusOK, res.Success(access))
	})
	//通过id获取
	g.GET("/getById/:id", func(c *gin.Context) {
		idInt, _ := strconv.Atoi(c.Param("id"))
		var access = accessDao.GetById(int64(idInt))
		c.JSON(http.StatusOK, res.Success(access))
	})
}
